import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { copyFileSync, mkdirSync, existsSync } from 'fs'

export default defineConfig({
    plugins: [
        vue(),
        // 自定义插件来处理 Chrome 扩展相关文件
        {
            name: 'chrome-extension',
            generateBundle() {
                // 确保 dist 目录存在
                if (!existsSync('dist')) {
                    mkdirSync('dist', { recursive: true })
                }
                // 复制 manifest.json
                copyFileSync('manifest.json', 'dist/manifest.json')
            }
        }
    ],
    build: {
        rollupOptions: {
            input: {
                popup: resolve(__dirname, 'popup.html'),
                editor: resolve(__dirname, 'editor.html'),
                background: resolve(__dirname, 'background.js'),
            },
            output: {
                entryFileNames: '[name].js',
                chunkFileNames: (chunkInfo) => {
                    // 避免以下划线开头的文件名，Chrome 扩展不允许
                    const name = chunkInfo.name;
                    if (name.startsWith('_')) {
                        return `vendor-${name.slice(1)}.js`;
                    }
                    return `${name}.js`;
                },
                assetFileNames: '[name].[ext]'
            }
        },
        outDir: 'dist',
        emptyOutDir: true,
        // 确保生成相对路径
        assetsDir: '',
    },
    define: {
        'process.env': {}
    },
    // 确保 CSS 和其他资源正确处理
    publicDir: false
})